package ipmss.services.authorities;

import ipmss.dao.authorities.UserDao;
import ipmss.dao.common.ApplicationConfigDao;
import ipmss.data.messages.Email;
import ipmss.entity.authorities.User;
import ipmss.entity.authorities.UserSettings;
import ipmss.entity.messages.EMailTemplate;
import ipmss.security.Authorities;
import ipmss.security.MyMessageDigest;
import ipmss.services.messages.Messages;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Properties;
import java.util.Random;

import javax.inject.Inject;
import javax.inject.Named;
import javax.mail.MessagingException;

import org.springframework.security.access.annotation.Secured;

// TODO: Auto-generated Javadoc
/**
 * The Class UsersManagementServiceBean.
 * 
 * @author Michał Czarnik
 */
@Named
public class UsersManagementServiceBean implements UsersManagementService
{

    /** The message digest. */
    private MyMessageDigest messageDigest;
    
    /** The rand. */
    private Random rand =  new Random();
    
    /** The messages. */
    @Inject
    private Messages messages;

    /** The user dao. */
    @Inject
    private UserDao userDao;

    /** The application config dao. */
    @Inject
    private ApplicationConfigDao applicationConfigDao;

    
    /**
     * Instantiates a new users management service bean.
     *
     * @throws NoSuchAlgorithmException the no such algorithm exception
     */
    public UsersManagementServiceBean() throws NoSuchAlgorithmException
    {
	messageDigest =  new MyMessageDigest("SHA");
    }
    

    /* (non-Javadoc)
     * @see ipmss.services.authorities.UsersManagementService#getUsers()
     */
    public List<User> getUsers()
    {
	return userDao.getAllUsers();
    }
    
    /**
     * Create new User, generate password and send login data on email.
     *
     * @param user the user
     * @throws MessagingException the messaging exception
     */
    public void createUser(User user) throws MessagingException
    {
	EMailTemplate template = applicationConfigDao.getEmailTempalte(EMailTemplate.NAME_CREATE_USER);
	Properties prop = new Properties();
	prop.setProperty(EMailTemplate.VAR_LOGIN,user.getLogin());
	prop.setProperty(EMailTemplate.VAR_LOGIN2,user.geteMail());
	String password = generatePasword(14);	
	String salt = generatePasword(14);
	prop.setProperty(EMailTemplate.VAR_PASSWORD,password);
	user.setSalt(salt);
	user.setPassword(hashPassword(password, salt));
	UserSettings settings =  new UserSettings();
	settings.setCurrentProjectId(-1);
	settings.setCurrentDesktopId(-1);
	user.setSettings(settings);
	userDao.addUser(user);
	Email email = new Email(template,prop);
	messages.sendEmail(email,user.geteMail());
    }

    /* (non-Javadoc)
     * @see ipmss.services.authorities.UsersManagementService#generatePasword(int)
     */
    public String generatePasword(int length)
    {
	StringBuilder pass = new StringBuilder();
	for(int i = 0 ; i < length ; i++)
	{
	    Character character = new Character('a');
	
	    if(rand.nextBoolean())	
		pass.append((char)('a' + rand.nextInt(24)));
	    else
		pass.append((char)('A' + rand.nextInt(24)));
	}
	return pass.toString();
    }
    
    /**
     * soli hasło i zwraca hash (sha1).
     *
     * @param password the password
     * @param salt the salt
     * @return the string
     */
    public String hashPassword(String password, String salt)
    {
	StringBuilder sb = new StringBuilder();

	char[] saltArray = salt.toCharArray();
	for (int i = 0; i < saltArray.length; i++)
	{
	    if (saltArray[i] < 'g')
	    {
		saltArray[i] += 2;
	    }
	}
	char[] passwordArray = password.toCharArray();
	for (int i = 0; i < salt.length() || i < password.length(); i++)
	{
	    if (i < password.length())
		sb.append(passwordArray[i]);
	    if (i < salt.length())
		sb.append(saltArray[i]);
	}

	try
	{
	    return messageDigest.convertMessage(sb.toString());
	} catch (UnsupportedEncodingException e)
	{
	    e.printStackTrace();
	}
	return null;

    }


    /* (non-Javadoc)
     * @see ipmss.services.authorities.UsersManagementService#saveUser(ipmss.entity.authorities.User)
     */
    public void saveUser(User u)
    {
	userDao.saveUser(u);
	
    }

}
